package com.rxt.thermopro.app

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import com.rxt.ble.BleManager
import com.rxt.ble.callback.BleScanCallback
import com.rxt.ble.data.BleDevice
import com.rxt.ble.data.BleScanState
import com.rxt.ble.scan.BleScanRuleConfig
import com.rxt.thermopro.adapter.DeviceListAdapter
import com.rxt.thermopro.bean.DeviceBean
import com.rxt.thermopro.bean.ProbeBean
import com.rxt.thermopro.viewmodel.BleMessageViewModel
import kotlinx.coroutines.*

class AppService : Service() {

    private val mBinder: IBinder = LocalBinder()

    override fun onBind(intent: Intent?): IBinder {
        return mBinder
    }

    inner class LocalBinder : Binder() {
        // Return this instance of LocalService so clients can call public methods
        val service: AppService
            get() = this@AppService
    }

    private var mBleViewModel: BleMessageViewModel? = null
    private val job = Job()
    private val serviceScope = CoroutineScope(Dispatchers.Main + job)

    @Volatile
    private var running = false

    fun startCheckConnectWorking(activity: FragmentActivity) {
        running = true
        println("======>  startCheckConnectWorking $running")
        try {
            mBleViewModel =
                ViewModelProvider(activity).get(BleMessageViewModel::class.java)
            //定时消息
            startLoopMsg()

            serviceScope.launch {
//                withContext(Dispatchers.Main) {
//                    searchBluetooth()
//                }
//                delay(15000)
                withContext(Dispatchers.IO) {
                    while (running) {
                        val list = LocalDataDao.INSTANCE.getDeviceList()
                        val connectedList = BleManager.getInstance().allConnectedDevice
                        println("======> AppService initDeviceData $list  connectedList=${connectedList.size}")
                        if (list.isNotEmpty() && BleManager.getInstance().isBlueEnable) {
                            val needConnectList = mutableListOf<DeviceBean>()
                            if (connectedList.isEmpty()) {
                                needConnectList.addAll(list)
                            } else {
                                needConnectList.addAll(list)
                                connectedList.forEach {
                                    println("======>  connectedList ${it.name}   ${it.mac}")
                                    val list1 = list.filter { item -> item.address == it.mac }
                                    if (list1.isNotEmpty()) {
                                        needConnectList.removeAll(list1)
                                    }
                                }
                            }
                            withContext(Dispatchers.Main) {
                                println("======>  needConnectList $needConnectList")
                                needConnectList.forEach { itemBean ->
                                    mBleViewModel?.connectBluetooth(
                                        ProbeBean(
                                            name = itemBean.name ?: "",
                                            address = itemBean.address
                                        )
                                    )
                                    delay(6000)
                                }
                            }
                        }
                        delay(6000)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 需要定时查询的数据
     */
    private fun startLoopMsg() {
        serviceScope.launch {
            withContext(Dispatchers.IO) {
                while (running) {
                    val list = LocalDataDao.INSTANCE.getDeviceList()
                    val connectedList = BleManager.getInstance().allConnectedDevice
                    if (connectedList.isNotEmpty() && list.isNotEmpty()) {
                        //查询电量
                        connectedList.forEach {
                            val filterList = list.filter { item -> item.address == it.mac }
                            if (filterList.isNotEmpty()) {
                                val connectedDevice =
                                    list.first { item -> item.address == it.mac }
                                if (connectedDevice.name?.contains("tp960", true) == true) {
                                    withContext(Dispatchers.Main) {
                                        mBleViewModel?.getBoxProbeBattery(it.mac)
                                        println("======> AppService getBoxProbeBattery")
                                    }
                                }
                            }
                        }
                    }
                    delay(5000)
                }
            }
        }
    }

    fun stopWorking() {
        running = false
    }

    fun isWorking():Boolean {
        return running
    }

    override fun onDestroy() {
        running = false
        serviceScope.cancel()
        mBleViewModel?.reConnectService?.postValue(System.currentTimeMillis())
        super.onDestroy()
    }

}